from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, HttpResponse
from django.conf import settings
from django.http import JsonResponse
from django_redis import get_redis_connection


class Context:
    """用户数据"""

    def __init__(self, username, role):
        self.username = username
        self.role = role


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.path_info in [
            '/login/' , '/test/'] or 'static' in request.path_info or 'media' in request.path_info or 'api' in request.path_info:
            return
        user = request.session.get('user_info')

        if not user:
            print('无用户')
            return redirect('login')

        # 访问数量
        conn = get_redis_connection('serve')
        nums = conn.get('click_nums')
        if nums is None:
            conn.set('click_nums', 0)
        else:
            nums = int(nums)
            nums += 1
            conn.set('click_nums', nums)

        request.nums = nums
        request.user = Context(**user)
        return
